package com.raja.servingStation.dao;

import com.raja.servingStation.datasources.RepairSql2oTemp;
import com.raja.servingStation.datasources.Sql2oConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.sql2o.Connection;
import org.sql2o.Query;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/26/026.
 */
@Repository
public class TestRepairDao {

    @Autowired
    private RepairSql2oTemp repairSql2oTemp;

    /**
     * 不需要事务的列子
     * @throws Exception
     */
    public void save() throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into raja_userinfo (name) values ('123123123')");
        try (Connection con = repairSql2oTemp.getSql2o().open()) {
            Query query = Sql2oConnection.createQuery(con,sb.toString());
            query.executeUpdate();
        }
    }


    /**
     * 需要事务的列子：
     */
    public void insert() throws Exception{
        try (Connection con = repairSql2oTemp.getSql2o().beginTransaction()) {
            // 插入工单表
            insertOrder(con);
            // 更新子任务状态
            insertOrderLog(con);
            //委托工单

            con.commit();
        } finally {
            repairSql2oTemp.setAutoCommit(true);
        }
    }

    private void insertOrder(Connection con) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("update test set name = 'hhhhhhhhh' ");
            Query query = Sql2oConnection.createQuery(con,sb.toString());
            query.executeUpdate();
    }
    private void insertOrderLog(Connection con) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("insert into raja_userinfo (name1) values ('123123123')");
            Query query = Sql2oConnection.createQuery(con,sb.toString());
            query.executeUpdate();
    }

    public Object test() throws Exception {
        String sql = "select count(*) from raja_userinfo  ";
        try (Connection con = repairSql2oTemp.getSql2o().open()) {
            Query query = Sql2oConnection.createQuery(con,sql);
            return query.executeScalar();
        }
    }
    public void update() throws Exception {
        insert();
    }
}
